<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class LocationTest extends BaseController
{
    /**
     * 测试定位和距离计算功能
     */
    public function testLocation()
    {
        // 获取请求参数
        $currentLat = Request::param('lat', 0); // 当前纬度
        $currentLng = Request::param('lng', 0); // 当前经度
        $currentLocation = Request::param('location', ''); // 格式: "lng,lat"
        $autoDetect = Request::param('auto', 0); // 是否自动获取IP定位
        
        // 获取考勤设置
        $setting = Db::name('checkin_setting')
            ->where('status', 1)
            ->order('id', 'desc')
            ->find();
        
        $result = [
            '定位测试详情' => '',
            '1. 请求参数' => [
                'lat (纬度)' => $currentLat,
                'lng (经度)' => $currentLng, 
                'location (经纬度字符串)' => $currentLocation,
                'auto (自动IP定位)' => $autoDetect
            ],
            '2. 考勤设置' => $setting ? [
                'ID' => $setting['id'],
                '打卡地点坐标' => $setting['location'],
                '打卡范围(米)' => $setting['range'],
                '地点名称' => $setting['location_name']
            ] : '未找到考勤设置',
            '3. 坐标解析' => [],
            '4. 距离计算' => [],
            '5. IP定位信息' => []
        ];
        
        // 如果启用自动IP定位
        if ($autoDetect) {
            $ipLocation = $this->getLocationByIP();
            $result['5. IP定位信息'] = $ipLocation;
            
            // 如果IP定位失败且是本地环境，提供模拟坐标
            if (!$ipLocation['success'] && ($ipLocation['ip'] === '127.0.0.1' || strpos($ipLocation['ip'], '192.168.') === 0)) {
                $result['5. IP定位信息']['本地环境提示'] = '检测到本地环境，无法进行IP定位';
                $result['5. IP定位信息']['建议'] = [
                    '1. 部署到公网服务器测试真实IP定位',
                    '2. 使用手机热点连接电脑测试',
                    '3. 手动输入坐标进行功能测试'
                ];
                
                // 提供一些测试用的坐标示例
                $result['5. IP定位信息']['测试坐标示例'] = [
                    '郑州市中心' => '113.625368,34.746611',
                    '北京市中心' => '116.407526,39.904030',
                    '上海市中心' => '121.473701,31.230416',
                    '广州市中心' => '113.264385,23.129163'
                ];
            }
            
            // 如果IP定位成功，使用IP定位结果
            if ($ipLocation['success'] && !$currentLocation) {
                $currentLocation = $ipLocation['lng'] . ',' . $ipLocation['lat'];
                $currentLng = $ipLocation['lng'];
                $currentLat = $ipLocation['lat'];
                
                $result['1. 请求参数']['使用IP定位坐标'] = $currentLocation;
            }
        }
        
        if ($setting && $setting['location']) {
            // 解析设置中的坐标
            $settingCoords = explode(',', $setting['location']);
            $result['3. 坐标解析']['设置坐标解析'] = [
                '原始字符串' => $setting['location'],
                '分割后数组' => $settingCoords,
                '数组长度' => count($settingCoords)
            ];
            
            if (count($settingCoords) === 2) {
                $settingLng = (float)$settingCoords[0];
                $settingLat = (float)$settingCoords[1];
                
                $result['3. 坐标解析']['设置坐标'] = [
                    '经度 (lng)' => $settingLng,
                    '纬度 (lat)' => $settingLat
                ];
            }
            
            // 如果有当前位置参数，进行距离计算
            if ($currentLocation) {
                $currentCoords = explode(',', $currentLocation);
                $result['3. 坐标解析']['当前坐标解析'] = [
                    '原始字符串' => $currentLocation,
                    '分割后数组' => $currentCoords,
                    '数组长度' => count($currentCoords)
                ];
                
                if (count($currentCoords) === 2) {
                    $currentLng = (float)$currentCoords[0];
                    $currentLat = (float)$currentCoords[1];
                    
                    $result['3. 坐标解析']['当前坐标'] = [
                        '经度 (lng)' => $currentLng,
                        '纬度 (lat)' => $currentLat
                    ];
                    
                    // 计算距离
                    $distance = $this->calculateDistance($currentLocation, $setting['location']);
                    $distance2 = $this->calculateDistanceByCoords($currentLat, $currentLng, $settingLat, $settingLng);
                    
                    $result['4. 距离计算'] = [
                        '方法1 (字符串)' => $distance . '米',
                        '方法2 (坐标)' => $distance2 . '米',
                        '是否在范围内' => $distance <= $setting['range'] ? '是' : '否',
                        '计算详情' => [
                            '当前位置' => "经度: {$currentLng}, 纬度: {$currentLat}",
                            '目标位置' => "经度: {$settingLng}, 纬度: {$settingLat}",
                            '经度差' => abs($currentLng - $settingLng),
                            '纬度差' => abs($currentLat - $settingLat)
                        ]
                    ];
                }
            } else if ($currentLat && $currentLng) {
                // 使用单独的经纬度参数
                $result['3. 坐标解析']['当前坐标'] = [
                    '经度 (lng)' => $currentLng,
                    '纬度 (lat)' => $currentLat
                ];
                
                if (count($settingCoords) === 2) {
                    $settingLng = (float)$settingCoords[0];
                    $settingLat = (float)$settingCoords[1];
                    
                    $distance = $this->calculateDistanceByCoords($currentLat, $currentLng, $settingLat, $settingLng);
                    
                    $result['4. 距离计算'] = [
                        '计算距离' => $distance . '米',
                        '是否在范围内' => $distance <= $setting['range'] ? '是' : '否',
                        '计算详情' => [
                            '当前位置' => "经度: {$currentLng}, 纬度: {$currentLat}",
                            '目标位置' => "经度: {$settingLng}, 纬度: {$settingLat}",
                            '经度差' => abs($currentLng - $settingLng),
                            '纬度差' => abs($currentLat - $settingLat)
                        ]
                    ];
                }
            }
        }
        
        // 添加使用说明
        $result['使用说明'] = [
            '测试URL示例1' => '/api.php/locationTest/testLocation?lat=34.815897&lng=113.335851',
            '测试URL示例2' => '/api.php/locationTest/testLocation?location=113.335851,34.815897',
            '自动IP定位' => '/api.php/locationTest/testLocation?auto=1',
            '说明' => '请在URL中传入你的当前经纬度进行测试，或使用auto=1自动获取IP定位'
        ];
        
        // 输出详细信息
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }
    
    /**
     * 计算两点间距离（使用字符串坐标）
     */
    private function calculateDistance($location1, $location2)
    {
        $coords1 = explode(',', $location1);
        $coords2 = explode(',', $location2);
        
        if (count($coords1) !== 2 || count($coords2) !== 2) {
            return 9999; // 坐标格式错误，返回一个大值
        }
        
        $lat1 = (float)$coords1[1];
        $lng1 = (float)$coords1[0];
        $lat2 = (float)$coords2[1];
        $lng2 = (float)$coords2[0];
        
        return $this->calculateDistanceByCoords($lat1, $lng1, $lat2, $lng2);
    }
    
    /**
     * 计算两点间距离（使用坐标参数）
     */
    private function calculateDistanceByCoords($lat1, $lng1, $lat2, $lng2)
    {
        $R = 6371000; // 地球半径，单位米
        $dLat = deg2rad($lat2 - $lat1);
        $dLng = deg2rad($lng2 - $lng1);
        
        $a = sin($dLat/2) * sin($dLat/2) +
             cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
             sin($dLng/2) * sin($dLng/2);
        
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        
        return round($R * $c);
    }
    
    /**
     * 通过IP获取位置信息
     */
    private function getLocationByIP()
    {
        try {
            // 获取客户端真实IP
            $ip = $this->getRealIP();
            
            // 使用免费的IP定位API
            $apiUrl = "http://ip-api.com/json/{$ip}?lang=zh-CN";
            $response = file_get_contents($apiUrl);
            
            if ($response === false) {
                return [
                    'success' => false,
                    'error' => '无法连接到定位服务',
                    'ip' => $ip
                ];
            }
            
            $data = json_decode($response, true);
            
            if ($data && $data['status'] === 'success') {
                return [
                    'success' => true,
                    'ip' => $ip,
                    'country' => $data['country'] ?? '',
                    'region' => $data['regionName'] ?? '',
                    'city' => $data['city'] ?? '',
                    'lat' => (float)$data['lat'],
                    'lng' => (float)$data['lon'],
                    'isp' => $data['isp'] ?? '',
                    'timezone' => $data['timezone'] ?? '',
                    'full_address' => ($data['country'] ?? '') . ' ' . ($data['regionName'] ?? '') . ' ' . ($data['city'] ?? '')
                ];
            } else {
                return [
                    'success' => false,
                    'error' => $data['message'] ?? '定位失败',
                    'ip' => $ip
                ];
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => '定位服务异常: ' . $e->getMessage(),
                'ip' => $this->getRealIP()
            ];
        }
    }
    
    /**
     * 获取客户端真实IP
     */
    private function getRealIP()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
            return $_SERVER['HTTP_X_REAL_IP'];
        } else {
            return $_SERVER['REMOTE_ADDR'];
        }
    }
}
